package com.action;

import cn.hutool.core.io.resource.MultiFileResource;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@CrossOrigin("*")
public class UploadAction {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    private String tmp="d:/tmp";

    @RequestMapping("/upload")
    public String  upload(MultipartFile  file) throws IOException {
        //得到原来的文件名  xxxx.jpg
        String oldFileName = file.getOriginalFilename();
        //得到一个最后一个.的位置
        int index = oldFileName.lastIndexOf('.');
        //得到后辍名
        String extName = oldFileName.substring(index);
        //新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //传到tmp目录
        File descFile = new File(tmp, newFileName);
        file.transferTo(descFile);

        //识别图片（银行卡)
        String url = "https://api.weixin.qq.com/cv/ocr/bankcard?type=MODE&access_token=%s";
        String token = (String) redisTemplate.boundValueOps("token").get();
        String newUrl = String.format(url, token);

        FileSystemResource resources = new FileSystemResource(descFile);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file",resources);

       String result=  restTemplate.postForObject(newUrl, form, String.class);
       String id = JSONObject.parseObject(result).getString("number");
        System.out.println(id);

       return id;
    }
}
